<?php

m2import('phpinchains/ActionForm.php');

/**
 * Core class with static factory methods for starting and running Chains application
 */
class PHPinChains {

/**
 * copiles the config file to php. it than can be loaded with include_once with
 * filename <config-filename>.php
 * @param string file Full name and path of main config file
 */
    function compileConfigFile($file) {
        PHPinChains::compileFile($file, array('conf'));
    }

    /**
     * Compiles a file with the given namespaces
     */
    function compileFile ($file, $namespaces, $parsertype = 'conf') {
        $env = env::getInstance();
        if (file_exists($file)) {
            if (file_exists($file.'.php')) {
                $cfile = stat($file.'.php');
                $sfile = stat($file);
                // mtime comparison
                if ($cfile[9] < $sfile[9]) {
                    $conlex = new phpinchains_parser_psp_PSPLexer($namespaces, file_get_contents($file), $file);
                    $conlex->lex();
                    if ($parsertype == 'conf')
                        $config = new phpinchains_parser_conf_ConfParser($conlex, '');
                    elseif ($parsertype == 'psp')
                        $config = new phpinchains_parser_psp_PSPParser($conlex, dirname($file).'/');
                    else
                        $config = new phpinchains_parser_conf_ConfParser($conlex, '');
                    $config->parse();
                    file_put_contents($file.'.php', '<?'.'php '."\n".$config->getCode()."\n?".'>');
                }
            } else {
                $conlex = new phpinchains_parser_psp_PSPLexer($namespaces, file_get_contents($file), $file);
                $conlex->lex();
                if ($parsertype == 'conf')
                    $config = new phpinchains_parser_conf_ConfParser($conlex, '');
                elseif ($parsertype == 'psp')
                    $config = new phpinchains_parser_psp_PSPParser($conlex, dirname($file).'/');
                else
                    $config = new phpinchains_parser_conf_ConfParser($conlex, '');
                $config->parse();
                file_put_contents($file.'.php', '<?'.'php '."\n".$config->getCode()."\n?".'>');
            }
        } else {
            trigger_error("FILE DOES NOT EXIST: file '$file' to compile does not exist.", E_USER_ERROR);
        }
    }

    function prepareChain($file) {
        PHPinChains::compileConfigFile($file);
    }

    function prepareAndStartChain($file) {
        $env = env::getInstance();
        PHPinChains::prepareChain($file);
        $actionform = new phpinchains_ActionForm();
        // FIXME: warum war hier include_once? Seiteneffekte mit include?
        include($file.'.php');
    }

}
?>